/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stuff.ext;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.codehaus.jackson.map.ObjectMapper;


/**
 *
 * @author Николай
 */
public class JSONRequestDataBinder extends WebDataBinder {

    private static ObjectMapper mapper = new ObjectMapper();

    public JSONRequestDataBinder(Object target) {
        super(target);
    }

    public JSONRequestDataBinder(Object target, String objectName) {
        super(target, objectName);
    }

    public void bind(HttpServletRequest request) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            MutablePropertyValues mpvs = new MutablePropertyValues(mapper.readValue(is, Map.class));
            doBind(mpvs);
        } catch (IOException ex) {
//            logger.error(ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
  //              logger.error(ex);
            }
        }
    }

    public void closeNoCatch() throws BindException {
        if (getBindingResult().hasErrors()) {
            throw new BindException(getBindingResult());
        }
    }
}
